package com.micro.ai.template.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.micro.ai.commons.domain.ApiResponse;
import com.micro.ai.commons.exception.BusinessException;
import com.micro.ai.template.entity.WorkflowDefinition;
import com.micro.ai.template.entity.WorkflowExecution;
import com.micro.ai.template.mapper.WorkflowDefinitionMapper;
import com.micro.ai.template.mapper.WorkflowExecutionMapper;
import com.micro.ai.template.service.WorkflowService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Map;

/**
 * 工作流服务实现
 *
 * @author micro-ai
 * @since 0.0.1
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class WorkflowServiceImpl extends ServiceImpl<WorkflowDefinitionMapper, WorkflowDefinition>
        implements WorkflowService {

    private final WorkflowExecutionMapper workflowExecutionMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ApiResponse<WorkflowDefinition> createWorkflow(WorkflowDefinition workflow) {
        log.info("创建工作流, name: {}", workflow.getWorkflowName());
        
        workflow.setCreatedAt(LocalDateTime.now());
        workflow.setUpdatedAt(LocalDateTime.now());
        
        this.save(workflow);
        log.info("工作流创建成功, workflowId: {}", workflow.getId());
        
        return ApiResponse.success(workflow);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ApiResponse<WorkflowDefinition> updateWorkflow(String workflowId, WorkflowDefinition workflow) {
        log.info("更新工作流, workflowId: {}", workflowId);
        
        WorkflowDefinition existing = this.getById(workflowId);
        if (existing == null) {
            throw new BusinessException("工作流不存在");
        }
        
        workflow.setId(workflowId);
        workflow.setUpdatedAt(LocalDateTime.now());
        
        this.updateById(workflow);
        log.info("工作流更新成功");
        
        return ApiResponse.success(workflow);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ApiResponse<Void> deleteWorkflow(String workflowId) {
        log.info("删除工作流, workflowId: {}", workflowId);
        
        WorkflowDefinition workflow = this.getById(workflowId);
        if (workflow == null) {
            throw new BusinessException("工作流不存在");
        }
        
        this.removeById(workflowId);
        log.info("工作流删除成功");
        
        return ApiResponse.<Void>success(null);
    }

    @Override
    public ApiResponse<WorkflowDefinition> getWorkflowById(String workflowId) {
        WorkflowDefinition workflow = this.getById(workflowId);
        if (workflow == null) {
            throw new BusinessException("工作流不存在");
        }
        
        return ApiResponse.success(workflow);
    }

    @Override
    public ApiResponse<Page<WorkflowDefinition>> listWorkflows(Integer pageNum, Integer pageSize, Map<String, Object> params) {
        Page<WorkflowDefinition> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<WorkflowDefinition> wrapper = new LambdaQueryWrapper<>();
        
        // 根据参数构建查询条件
        if (params != null) {
            String name = (String) params.get("name");
            if (name != null && !name.isEmpty()) {
                wrapper.like(WorkflowDefinition::getWorkflowName, name);
            }
            
            Boolean enabled = (Boolean) params.get("enabled");
            if (enabled != null) {
                wrapper.eq(WorkflowDefinition::getEnabled, enabled);
            }
        }
        
        wrapper.orderByDesc(WorkflowDefinition::getCreatedAt);
        
        Page<WorkflowDefinition> result = this.page(page, wrapper);
        return ApiResponse.success(result);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ApiResponse<WorkflowExecution> executeWorkflow(String workflowId, Map<String, Object> inputData) {
        log.info("执行工作流, workflowId: {}", workflowId);
        
        WorkflowDefinition workflow = this.getById(workflowId);
        if (workflow == null) {
            throw new BusinessException("工作流不存在");
        }
        
        // 创建执行记录
        WorkflowExecution execution = new WorkflowExecution();
        execution.setWorkflowId(workflowId);
        execution.setInputData(inputData);
        execution.setStatus("RUNNING");
        execution.setCreatedAt(LocalDateTime.now());
        
        workflowExecutionMapper.insert(execution);
        log.info("工作流执行开始, executionId: {}", execution.getId());
        
        // TODO: 异步执行工作流逻辑
        
        return ApiResponse.success(execution);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ApiResponse<Void> cancelExecution(String executionId) {
        log.info("取消工作流执行, executionId: {}", executionId);
        
        WorkflowExecution execution = workflowExecutionMapper.selectById(executionId);
        if (execution == null) {
            throw new BusinessException("执行记录不存在");
        }
        
        execution.setStatus("CANCELLED");
        execution.setCompletedAt(LocalDateTime.now());
        workflowExecutionMapper.updateById(execution);
        
        log.info("工作流执行已取消");
        return ApiResponse.<Void>success(null);
    }

    @Override
    public ApiResponse<WorkflowExecution> getExecutionById(String executionId) {
        WorkflowExecution execution = workflowExecutionMapper.selectById(executionId);
        if (execution == null) {
            throw new BusinessException("执行记录不存在");
        }
        
        return ApiResponse.success(execution);
    }

    @Override
    public ApiResponse<Page<WorkflowExecution>> listExecutionHistory(String workflowId, Integer pageNum, Integer pageSize) {
        Page<WorkflowExecution> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<WorkflowExecution> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WorkflowExecution::getWorkflowId, workflowId)
                .orderByDesc(WorkflowExecution::getCreatedAt);
        
        Page<WorkflowExecution> result = new Page<>();
        result.setRecords(workflowExecutionMapper.selectPage(page, wrapper).getRecords());
        result.setTotal(workflowExecutionMapper.selectCount(wrapper));
        result.setCurrent(pageNum);
        result.setSize(pageSize);
        
        return ApiResponse.success(result);
    }
}

